package the.world.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import the.world.bean.Comment;
import the.world.bean.MessageList;
import the.world.bean.Navigation;
import the.world.bean.User;
import the.world.service.impl.CommentServiceImpl;
import the.world.service.impl.GuiServiceImpl;
import the.world.service.impl.ListServiceImpl;
import the.world.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class CommentController {
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private GuiServiceImpl guiService;

    @GetMapping("/comment/select")
    public ModelAndView sel(HttpSession session){
        List<Comment> comments = commentService.selectAll();
        List<Map<String, Object>> commentList = new ArrayList<Map<String, Object>>();
        List<Navigation> navigationPath = guiService.getNavigationPath("exchange");
        for (Comment comment : comments) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("comment", comment);
            User user = userService.selectById(comment.getUid());
            map.put("user", user);
            commentList.add(map);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("navigationPath", navigationPath);
        modelAndView.addObject("commentList", commentList);
        modelAndView.setViewName("exchange");
        return modelAndView;
    }

    @PostMapping("/comment/add/{id}")
    public ModelAndView add(@PathVariable("id") int id, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String context = request.getParameter("context");
        context = URLDecoder.decode(context, "UTF-8");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        int flag = commentService.insertContext(new Comment(id, simpleDateFormat.format(date), context));
        ModelAndView modelAndView = new ModelAndView();
        if (flag > 0){
            modelAndView.setViewName("redirect:/comment/select");
        } else {
            modelAndView.setViewName("redirect:/comment/select");
        }
        return modelAndView;
    }
}
